<template>
  <div class="base-chart">
    <div ref="echartDivRef" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watchEffect, watch } from 'vue'
import useEchart from './hooks/useEchart'
import emitter from '@/utils/bus'
const props = defineProps({
  options: {
    type: Object,
    default: () => ({})
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  }
})

const echartDivRef = ref()
const gstyEchart = ref()

onMounted(() => {
  if (!gstyEchart.value) {
    gstyEchart.value = useEchart(echartDivRef.value)
  }

  watchEffect(() => {
    gstyEchart.value.setOptions(props.options)
  })

  emitter.on('initEcharts', () => {
    gstyEchart.value.echartInstance.resize()
  })
  emitter.on('clearEcharts', () => {
    gstyEchart.value.echartInstance.clear()
  })
  // 4.暴露实例
  emit('onload', gstyEchart.value.echartInstance)
})
watch(
  () => props.options,
  () => {
    gstyEchart.value.echartInstance.clear()
    gstyEchart.value.setOptions(props.options)
  },
  {
    deep: true
  }
)
const emit = defineEmits(['onload'])
onUnmounted(() => {
  emitter.off('initEcharts')
  emitter.off('clearEcharts')
  gstyEchart.value.echartInstance && gstyEchart.value.echartInstance.dispose()
})
</script>

<style lang="less" scoped>
.base-chart {
  width: 100%;
  height: 100%;
}
</style>
